#!/usr/bin/python
# -*- coding: UTF-8 -*-


import time,threading,sys
sys.path.append("/home/biowin/Minibot/04.RobotSamples/03.SpiderRobot")
from BwRobotLib import BwRobotLib
from SpiderRobot import SpiderRobot
from BwSensorLib import BwSensorLib
import os,inspect

# 加载机器人构型配置
fileName = inspect.getframeinfo(inspect.currentframe()).filename
folderPath     = os.path.dirname(os.path.abspath(fileName))
cfile=folderPath+"/config.txt"


class WelcomeRobot:
	def __init__(self):
		# 实例化传感器库对象
		self.sensorlib = BwsensorliblibLib("udp")
		# 实例化BwRobotLib库
		self.robotlib = BwRobotLib("udp")
		# 实例化蜘蛛机器人库
		self.spider = SpiderRobot(self.robotlib)
		# 连接机器人设备
		self.robotlib.connectRobot("10.10.100.254",8899) #真机AP模式
        # 导入机器人配置参数
        self.robotlib.loadConfig(config_file)
		#配置ID
		self.spider.bindIds(self.robotlib.module_ids)
		# 时间变量
		self.wait_time = 0.5
		# 蜘蛛机器人运动标志位
		self.flag_threading = 0 
		# 点阵显示
		# 开心 无表情　
		self.display_data = [[0x02,0x24,0x02,0x08,0x1C],[0x00,0x00,0x00,0x00,0x00]]
        # RGB彩灯参数
        # [255,1,1] 红色；[1,255,1] 绿色；[1,1,255] 蓝色；[1,1,1] 熄灯；
        self.rgb_value = [[255, 1, 1], [1, 255, 1], [1, 1, 255], [1, 1, 1]]

	def welcomeRobotDisplay(self):
		while 1:
			if(self.flag_threading==1):
				for a in range (0,1): # rgb灯亮红、绿、蓝两次循环
					self.sensor.setMatrixSensor(self.display_data [0]) # 点阵显示开心表情
					self.sensor.setRGBLightSensor(self.rgb_value[0]) # 亮红灯
					time.sleep(self.wait_time)
					self.sensor.setRGBLightSensor(self.rgb_value[1]) # 亮绿灯
					time.sleep(self.wait_time)
					self.sensor.setRGBLightSensor(self.rgb_value[2]) # 亮蓝灯
					time.sleep(self.wait_time)
			else:
				self.sensor.setMatrixSensor(self.display_data [1]) # 点阵无显示
				self.sensor.setRGBLightSensor(self.rgb_value[3]) # 灭灯
				
	
	def welcomeRobotMotion(self):
		# 创建线程对象
		self.threading_1 = threading.Thread(target=self.welcomeRobotDisplay, args=())       # 实例化rgb灯显示线程	
		# 开启线程
		self.threading_1.start()
		while 1:
			voice = self.sensorlib.readVoiceSensor() #读取声音传感器数据
			print("测量声音值为:%d" % voice) # 输出声音数值
			if (voice > 200):
				print("有声音")
				self.flag_threading = 1
				self.spider.sayHello() # 蜘蛛机器人打招呼
				self.flag_threading = 0
			else:
				print("没声音")
							
# 主函数
def main():
    # 实例化迎宾机器人类
    welcomeRobot = WelcomeRobot()
    # 执行迎宾机器人功能
    welcomeRobot.welcomeRobotMotion()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print(" Program closed! ")
    pass
